package org.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.entity.Employee;
import org.example.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 员工管理控制器
 * 提供员工相关的CRUD操作接口
 * 
 * @author 系统
 * @since 1.0
 */
@RestController
@RequestMapping("/employee")
@CrossOrigin(origins = "*")
public class EmployeeController {

    /**
     * 员工数据访问层
     */
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录接口
     * 
     * @param loginData 登录数据，包含用户名和密码
     * @return 登录结果，包含状态码、消息和员工信息
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginData) {
        Map<String, Object> result = new HashMap<>();

        // 获取登录参数
        String username = loginData.get("username");
        String password = loginData.get("password");

        // 密码MD5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        // 根据用户名查询员工信息
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, username);
        Employee employee = employeeMapper.selectOne(queryWrapper);

        // 验证用户名是否存在
        if (employee == null) {
            result.put("code", 0);
            result.put("msg", "用户名不存在");
            return result;
        }

        // 验证密码是否正确
        if (!employee.getPassword().equals(password)) {
            result.put("code", 0);
            result.put("msg", "密码错误");
            return result;
        }

        // 验证账号状态是否正常
        if (employee.getStatus() == 0) {
            result.put("code", 0);
            result.put("msg", "账号已被禁用");
            return result;
        }

        // 登录成功，返回员工信息
        result.put("code", 1);
        result.put("msg", "登录成功");
        result.put("data", employee);

        return result;
    }

    /**
     * 员工退出登录接口
     * 
     * @return 退出结果
     */
    @PostMapping("/logout")
    public Map<String, Object> logout() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "退出成功");
        return result;
    }

    /**
     * 分页查询员工列表
     * 
     * @param page 当前页码，默认为1
     * @param pageSize 每页大小，默认为10
     * @param name 员工姓名搜索条件，可选
     * @return 分页查询结果
     */
    @GetMapping("/page")
    public Map<String, Object> getEmployeePage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name) {

        Map<String, Object> result = new HashMap<>();

        // 创建分页对象
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Employee::getName, name);  // 按姓名模糊查询
        queryWrapper.orderByDesc(Employee::getUpdateTime);  // 按更新时间倒序

        // 调试信息输出
        System.out.println("分页参数 - 当前页: " + page + ", 每页大小: " + pageSize);
        System.out.println("分页参数 - 搜索条件: " + (name != null ? name : "无"));
        
        // 执行分页查询
        Page<Employee> employeePage = employeeMapper.selectPage(pageInfo, queryWrapper);
        
        System.out.println("分页查询结果 - 当前页: " + employeePage.getCurrent());
        System.out.println("分页查询结果 - 每页大小: " + employeePage.getSize());
        System.out.println("分页查询结果 - 实际返回记录数: " + employeePage.getRecords().size());
        
        // 手动查询总数，确保分页数据准确性
        Long totalCount = employeeMapper.selectCount(queryWrapper);
        System.out.println("手动查询的总数: " + totalCount);

        // 手动构建分页数据，确保total字段正确传递
        Map<String, Object> pageData = new HashMap<>();
        pageData.put("records", employeePage.getRecords());  // 当前页数据
        pageData.put("total", totalCount);  // 总记录数
        pageData.put("size", employeePage.getSize());  // 每页大小
        pageData.put("current", employeePage.getCurrent());  // 当前页
        pageData.put("pages", (totalCount + pageSize - 1) / pageSize);  // 总页数
        
        // 构建返回结果
        result.put("code", 1);
        result.put("msg", "查询成功");
        result.put("data", pageData);
        
        // 调试信息输出
        System.out.println("分页查询结果 - 总记录数: " + employeePage.getTotal());
        System.out.println("分页查询结果 - 当前页记录数: " + employeePage.getRecords().size());
        System.out.println("分页查询结果 - 当前页: " + employeePage.getCurrent());
        System.out.println("分页查询结果 - 每页大小: " + employeePage.getSize());
        System.out.println("手动构建的分页数据: " + pageData);

        return result;
    }
    /**
     * 根据ID查询员工信息
     * 
     * @param id 员工ID
     * @return 员工信息
     */
    @GetMapping("/{id}")
    public Map<String, Object> getEmployeeById(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            System.out.println("getEmployeeById - 查询员工ID: " + id);
            
            // 根据ID查询员工信息
            Employee employee = employeeMapper.selectById(id);
            System.out.println("getEmployeeById - 查询结果: " + (employee != null ? employee.getName() : "null"));
            
            if (employee != null) {
                result.put("code", 1);
                result.put("msg", "查询成功");
                result.put("data", employee);
            } else {
                result.put("code", 0);
                result.put("msg", "员工不存在");
            }
        } catch (Exception e) {
            result.put("code", 0);
            result.put("msg", "查询失败: " + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }
    /**
     * 添加新员工
     * 
     * @param employeeMap 员工信息Map
     * @return 添加结果
     */
    @PostMapping
    public Map<String, Object> addEmployee(@RequestBody Map<String, Object> employeeMap) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 创建Employee对象并设置属性
            Employee employee = new Employee();
            employee.setName((String) employeeMap.get("name"));
            employee.setUsername((String) employeeMap.get("username"));
            employee.setPhone((String) employeeMap.get("phone"));
            employee.setSex((String) employeeMap.get("sex"));
            employee.setIdNumber((String) employeeMap.get("idNumber"));
            
            // 设置默认密码为123456并进行MD5加密
            String defaultPassword = "123456";
            employee.setPassword(DigestUtils.md5DigestAsHex(defaultPassword.getBytes()));
            
            // 设置状态为1（启用）
            employee.setStatus(1);
            
            // 设置创建时间和更新时间
            LocalDateTime now = LocalDateTime.now();
            employee.setCreateTime(now);
            employee.setUpdateTime(now);
            
            // 设置创建人和更新人（这里假设从前端传入了当前登录用户的ID）
            Long currentUserId = employeeMap.get("currentUserId") != null ? 
                    Long.parseLong(employeeMap.get("currentUserId").toString()) : 1L;
            employee.setCreateUser(currentUserId);
            employee.setUpdateUser(currentUserId);
            
            // 保存到数据库
            int rows = employeeMapper.insert(employee);
            
            if (rows > 0) {
                result.put("code", 1);
                result.put("msg", "添加成功");
            } else {
                result.put("code", 0);
                result.put("msg", "添加失败");
            }
        } catch (Exception e) {
            result.put("code", 0);
            result.put("msg", "添加失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 更新员工信息
     * 
     * @param employeeMap 员工信息Map，必须包含id字段
     * @return 更新结果
     */
    @PutMapping
    public Map<String, Object> updateEmployee(@RequestBody Map<String, Object> employeeMap) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取员工ID，添加空值检查
            Object idObj = employeeMap.get("id");
            if (idObj == null) {
                result.put("code", 0);
                result.put("msg", "员工ID不能为空");
                return result;
            }
            
            System.out.println("updateEmployee - 接收到的ID: " + idObj + " (类型: " + idObj.getClass().getSimpleName() + ")");
            String id = idObj.toString();
            System.out.println("updateEmployee - 转换后的ID: " + id);
            
            // 查询员工是否存在
            Employee existingEmployee = employeeMapper.selectById(id);
            System.out.println("updateEmployee - 查询结果: " + existingEmployee);
            
            if (existingEmployee == null) {
                result.put("code", 0);
                result.put("msg", "员工不存在");
                return result;
            }
            
            // 创建更新条件
            LambdaUpdateWrapper<Employee> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Employee::getId, id);
            
            // 创建更新对象
            Employee employee = new Employee();
            
            // 添加空值检查，只更新非空字段
            if (employeeMap.get("name") != null) {
                employee.setName((String) employeeMap.get("name"));
            }
            
            if (employeeMap.get("username") != null) {
                employee.setUsername((String) employeeMap.get("username"));
            }
            
            if (employeeMap.get("phone") != null) {
                employee.setPhone((String) employeeMap.get("phone"));
            }
            
            if (employeeMap.get("sex") != null) {
                employee.setSex((String) employeeMap.get("sex"));
            }
            
            if (employeeMap.get("idNumber") != null) {
                employee.setIdNumber((String) employeeMap.get("idNumber"));
            }
            
            // 如果状态字段存在且非空，则更新状态
            if (employeeMap.containsKey("status") && employeeMap.get("status") != null) {
                employee.setStatus(Integer.parseInt(employeeMap.get("status").toString()));
            }
            
            // 设置更新时间
            employee.setUpdateTime(LocalDateTime.now());
            
            // 设置更新人，添加空值检查
            Long currentUserId = 1L; // 默认值
            if (employeeMap.get("currentUserId") != null) {
                currentUserId = Long.parseLong(employeeMap.get("currentUserId").toString());
            }
            employee.setUpdateUser(currentUserId);
            
            // 更新数据库
            int rows = employeeMapper.update(employee, updateWrapper);
            
            if (rows > 0) {
                result.put("code", 1);
                result.put("msg", "修改成功");
            } else {
                result.put("code", 0);
                result.put("msg", "修改失败");
            }
        } catch (Exception e) {
            result.put("code", 0);
            result.put("msg", "修改失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 批量更新员工状态
     * 
     * @param status 目标状态 (0:禁用 1:启用)
     * @param ids 员工ID列表，逗号分隔
     * @return 更新结果
     */
    @PostMapping("/status/{status}")
    public Map<String, Object> updateStatus(@PathVariable int status, @RequestParam String ids) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 1);
        result.put("msg", "状态修改成功");
        return result;
    }
}
